package com.tofine.smarthome.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.ActiveAndroid;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;
import com.squareup.picasso.Picasso;
import com.tofine.smarthome.R;
import com.tofine.smarthome.model.Device;
import com.tofine.smarthome.model.Scene;
import com.tofine.smarthome.model.SceneDevice;
import com.tofine.smarthome.rest.RestClient;
import com.tofine.smarthome.rest.model.Command;
import com.tofine.smarthome.ui.SceneInfoActivity;
import com.tofine.smarthome.util.CommandUtils;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author ddMax
 * @since 2016/5/3 20:38.
 */
public class SceneRecyclerViewAdapter extends RecyclerSwipeAdapter<SceneRecyclerViewAdapter.ViewHolder> {

    public static class ViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.swipe) SwipeLayout swipeLayout;
        @Bind(R.id.delete) ImageView deleteView;
        @Bind(R.id.scene_item) RelativeLayout mItem;
        @Bind(R.id.item_scene_image) ImageView mSceneImage;
        @Bind(R.id.scene_title) TextView mSceneTitle;
        @Bind(R.id.scene_switch) SwitchCompat mSceneSwitch;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private Context mContext;
    private List<Scene> mDataSet;

    public SceneRecyclerViewAdapter(Context context, List<Scene> dataSet) {
        this.mContext = context;
        this.mDataSet = dataSet;
    }

    /**
     * 创建ViewHolder
     * @param parent 对应的父视图
     * @param viewType 一个标志，我们根据该标志可以实现渲染不同类型的ViewHolder
     * @return ViewHolder对象
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_scene, parent, false);
        return new ViewHolder(view);
    }

    /**
     * 绑定每个ViewHolder的数据
     * @param holder 当前的ViewHolder实例
     * @param position ViewHolder实例的位置
     */
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final Scene scene = mDataSet.get(position);
        if (scene.image == null) {
            holder.mSceneImage.setVisibility(View.GONE);
        } else {
            Picasso.with(mContext).load(Uri.parse(scene.image)).into(holder.mSceneImage);
        }
        holder.mSceneTitle.setText(scene.name);
        holder.mSceneSwitch.setChecked(scene.status);
        holder.mSceneSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 取出该情景下的所有设备
                List<Device> devices = new Select().from(Device.class)
                        .innerJoin(SceneDevice.class).on("devices.id = scenedevice.device")
                        .where("scenedevice.scene = ?", scene.getId())
                        .execute();
                // 切换设备、情景状态并保存
                ActiveAndroid.beginTransaction();
                try {
                    for (final Device device : devices) {
                        device.status = isChecked;
                        RestClient.getInstance().getApiService().sendCommand(device._id, CommandUtils.genCommand(device)).enqueue(new Callback<Command>() {
                            @Override
                            public void onResponse(Call<Command> call, Response<Command> response) {
                                device.save();
                            }

                            @Override
                            public void onFailure(Call<Command> call, Throwable t) {
                                device.save();
                                t.printStackTrace();
                            }
                        });
                        device.save();
                    }
                    scene.status = isChecked;
                    scene.save();
                    ActiveAndroid.setTransactionSuccessful();
                } finally {
                    ActiveAndroid.endTransaction();
                }
                // Toast消息
                String message = isChecked ? scene.name + " 已启用" : scene.name + " 已关闭";
                Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
            }
        });
        holder.deleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 删除SceneDevice关系
                new Delete().from(SceneDevice.class).where("scene = " + scene.getId()).execute();
                scene.delete();
                mItemManger.removeShownLayouts(holder.swipeLayout);
                mDataSet.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, mDataSet.size());
                mItemManger.closeAllItems();
            }
        });
        holder.mItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SceneInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("scene_name", scene.name);
                intent.putExtras(bundle);
                mContext.startActivity(intent);
            }
        });
    }

    /**
     * Adapter中Item总数
     * @return Item总数
     */
    @Override
    public int getItemCount() {
        return mDataSet.size();
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe;
    }
}
